package com.mz.ieann.aide.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Outline
import android.graphics.Rect
import android.os.Build
import android.util.AttributeSet
import android.util.Log
import android.view.SurfaceView
import android.view.View
import android.view.ViewOutlineProvider
import com.mz.ieann.aide.R

/**
 * <p>------------------------------------------------------
 * <p> Copyright (C) 2021 zhangmz, All rights reserved.
 * <p> If there is technical discussion, you can contact zhangmz90@foxmail.com
 * <p>------------------------------------------------------
 * <p> 圆角的SurfaceView，只限5.0以上
 * <p>
 *
 * @author Created by zhangmz
 * @date on 2022/5/12
 */
open class RoundSurfaceView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0
): SurfaceView(context, attrs, defStyle) {

    private val radius = context.resources.getDimension(R.dimen.dp_100)

    init {
        // 未主动绘制view，需要调用该方法，才会知道draw()，再执行onDraw()
        setWillNotDraw(false)
        clipToOutline = true
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        Log.v("reward", "----->> RoundSurfaceView,onDraw,radius:$radius; canvas:$canvas")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            outlineProvider = object : ViewOutlineProvider() {
                override fun getOutline(view: View?, outline: Outline?) {
                    val rect = Rect().apply { view?.getGlobalVisibleRect(this) }
                    outline?.setRoundRect(Rect(0, 0, rect.width(), rect.height()), radius)
                }
            }
        }
    }

}